import json
import random
from datetime import datetime, timedelta

from django.contrib.auth import login, logout
from django.http import JsonResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from apps.firmUser.models import FirmUser
from apps.jobs.models import UserJobsCollect
from apps.user.models import User
from utils.jwtUtils import generate_jwt
from utils.myLoginView import MyLoginView
from utils.sms import send_sms

# 发送验证码
from utils.viewmixin import LoginMixin


class MobileVerCode(View):

    def get(self, request, mobile):
        # 发送验证码
        sms_code = '%06d' % random.randint(0, 999999)

        redis_conn = get_redis_connection('code')

        redis_conn.setex('mobile_%s' % mobile, 60 * 3, sms_code)

        send_sms.send_message(datas=(sms_code, '3'))
        # 缓存验证码

        # 返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok'})


# 注册
class RegisterUserView(View):

    def post(self, request):

        # 获取数据
        data = json.loads(request.body)
        name = data.get("name")
        mobile = data.get("mobile")
        code = data.get("code")
        isFirm = data.get("isFirm")
        # 判断手机号有没有登录
        if isFirm:
            count = FirmUser.objects.filter(mobile=mobile).count()
        else:
            count = User.objects.filter(mobile=mobile).count()

        if count > 0:
            return JsonResponse({
                "code": "400",
                "errmsg": "手机号已被注册请直接登录"
            })

        # 验证数据
        if not all([name, mobile, code]):
            return JsonResponse({"code": "400", "errmsg": "缺少参数"})
        # 验证手机验证码
        redis_conn = get_redis_connection('code')

        redis_coed = redis_conn.get('mobile_%s' % mobile)

        if not redis_coed:
            return JsonResponse({"code": "400", "errmsg": "验证码过期，请重新请求"})

        if redis_coed.decode() != str(code):
            return JsonResponse({"code": "400", "errmsg": "验证码错误，请重新请求"})

        # 写入数据库
        try:
            if isFirm:
                FirmUser.objects.create(username=name,mobile=mobile)
            else:
                User.objects.create(username=name, mobile=mobile)
        except:
            return JsonResponse({"code": "400", "errmsg": "注册失败"})

        response = JsonResponse({"code": "200", "errmsg": "ok"})
        # 返回响应
        return response


# 登录
class LoginUserView(View):
    def _generate_tokens(self, user_id, with_refresh_token=False):
        """
        生成token 和refresh_token
        :param user_id: 用户id
        :return: token, refresh_token
        """
        # 颁发JWT
        now = datetime.utcnow()
        expiry = now + timedelta(days=1)

        token = generate_jwt({'user_id': user_id, 'refresh': False}, expiry)
        # refresh_token = None
        # if with_refresh_token:
        #     refresh_expiry = now + timedelta(days=current_app.config['JWT_REFRESH_DAYS'])
        #     refresh_token = generate_jwt({'user_id': user_id, 'refresh': True}, refresh_expiry)
        # return token, refresh_token
        return token
    def post(self, request):
        # 获取数据
        data = json.loads(request.body)
        mobile = data.get("mobile")
        code = data.get("code")
        isFirm = data.get("isFirm")

        # 验证数据
        if not all([mobile, code]):
            return JsonResponse({"code": "400", "errmsg": "缺少参数"})
        # 验证手机验证码
        redis_conn = get_redis_connection('code')

        redis_coed = redis_conn.get('mobile_%s' % mobile)

        if not redis_coed:
            return JsonResponse({"code": "400", "errmsg": "验证码过期，请重新请求"})

        if redis_coed.decode() != str(code):
            return JsonResponse({"code": "400", "errmsg": "验证码错误，请重新请求"})

        # 查询数据库
        try:
            if isFirm:
                user = FirmUser.objects.filter(mobile=mobile).first()
            else:
                user = User.objects.filter(mobile=mobile).first()
        except:
            return JsonResponse({"code": "400", "errmsg": "登录失败"})

        if not user:
            return JsonResponse({"code": 400, "errmsg": "登录失败"})
        # 状态保持

        # 状态保持
        # TODO 签发Token
        token = self._generate_tokens(user.id)
        response = JsonResponse(
            {"code": "200", "errmsg": "ok", "data": {'token': token, 'username': user.username,'is_Firm':isFirm,"user_id":user.id}})

        # 返回响应
        return response


class LogoutUserView(MyLoginView):
    def get(self, request):

        response = JsonResponse({"code": "200", "errmsg": "ok"})


        return response


# 用户主页数据
class UserInfoView(MyLoginView):

    def get(self, request):
        user = request.user

        ret = {
            "id": user.id,
            "profess_name": user.profess_name,
            "work_exper": user.work_exper,
            "project": eval(user.project),
            "brief": user.brief,
            "jineng": str(user.jineng).split("-"),
            "name": user.username
        }

        return JsonResponse({"code": "200", "errmsg": "ok", "data": ret})


# 用户收藏数据
class UserCollectView(MyLoginView):

    # 获取
    def get(self, request):

        user = request.user

        ret = []
        for job in user.collect.all():
            obj = job.job
            ret.append({
                "id": obj.id,
                "collect_id": job.id,
                "name": obj.jobs_name,
                "explain": obj.jobs_explain,
                "type": obj.jobs_type,
                "max_salary": obj.jobs_max_salary,
                "min_salary": obj.jobs_min_salart,
                "province": obj.jobs_province.name,
                "city": obj.jobs_city.name,
                "district": obj.jobs_district.name,
                'user': obj.jobs_user.username,
                'look_count': obj.look_count,
                "collect": obj.collect.count()
            })

        return JsonResponse({"code": '200', "errmsg": 'ok', "data": ret})

    # 添加
    def post(self, request):
        data = json.loads(request.body)

        job_id = data.get('job_id')

        try:
            UserJobsCollect.objects.create(user=request.user, job_id=job_id)
        except Exception as e:
            print(e)
            return JsonResponse({"code": '400', 'errmsg': "保存失败"})

        return JsonResponse({"code": '200', 'errmsg': 'ok'})
    # 删除
    def delete(self, request):
        data = json.loads(request.body)

        job_id = data.get('collect_id')

        # 验证数据
        try:
            collect = UserJobsCollect.objects.get(user=request.user,job_id=job_id)
            collect.delete()
        except Exception as  e:
            print(e)
            return JsonResponse({"code": '400', "errmsg": '数据库异常'})

        return JsonResponse({"code": '200', "errmsg": 'ok'})

#
class UserCollectIdView(MyLoginView):

    def get(self,request):

        user = request.user

        data = [obj.job.id for obj in user.collect.all()]

        return JsonResponse({"code":'200','errmsg':'ok','data':data})